package com.ruoyi.activiti.utils;

import com.ruoyi.activiti.domain.vo.FlowType;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ActivitiUtils {

    @Autowired
    private TaskService taskService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private GatewayConditionService gatewayConditionService;

    /**
     * 判断下个节点的类型，排它网关、用户网关、包容网关等
     * @param taskId 任务节点id
     * @return 返回下个节点类型字符串
    * */
    public FlowElement nextFlowType(String taskId) {
        String nextElementType = "";
        FlowElement targetElement = null;
        // 1. 获取当前任务
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processDefinitionId = task.getProcessDefinitionId();

        // 2. 获取BPMN模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        Process process = bpmnModel.getMainProcess();

        // 3. 获取当前任务节点
        FlowElement currentElement = process.getFlowElement(task.getTaskDefinitionKey());
        if (!(currentElement instanceof UserTask)) {
            throw new IllegalArgumentException("当前节点不是用户任务");
        }

        // 4. 获取所有出线并解析目标节点
        List<SequenceFlow> outgoingFlows = ((UserTask) currentElement).getOutgoingFlows();
        if (outgoingFlows.isEmpty()) {
            nextElementType = FlowType.END_EVENT.getNodeType(); // 无出线说明流程结束
        }
        log.info("获取所有出线并解析目标节点:{}", outgoingFlows.size());
        // 5. 遍历出线（通常用户任务只有一条默认出线）
        for (SequenceFlow flow : outgoingFlows) {
            targetElement = process.getFlowElement(flow.getTargetRef());
            // 6. 判断目标节点类型
            if (targetElement instanceof ExclusiveGateway) {
                nextElementType = FlowType.EXCLUSIVE_GATEWAY.getNodeType();
            } else if (targetElement instanceof InclusiveGateway) {
                nextElementType =  FlowType.INCLUSIVE_GATEWAY.getNodeType();
            } else if (targetElement instanceof ParallelGateway) {
                nextElementType = FlowType.PARALLEL_GATEWAY.getNodeType();
            } else if (targetElement instanceof UserTask) {
                nextElementType = FlowType.USER_TASK.getNodeType();
            } else if (targetElement instanceof EndEvent) {
                nextElementType = FlowType.END_EVENT.getNodeType();
            }
            // 其他类型：ServiceTask, ScriptTask, CallActivity 等...
        }
        return targetElement;

    }

    /**
    * 获取表达式
    * */
    public List<GatewayConditionService.SequenceFlowCondition> printGatewayDetails(String procDefId,String gatewayId) {
        List<GatewayConditionService.SequenceFlowCondition> conditions =
                gatewayConditionService.getSequenceFlowConditions(procDefId, gatewayId);

        System.out.println("网关Gateway_1y22560 " + " 的序列流条件:");
        for (GatewayConditionService.SequenceFlowCondition condition : conditions) {
            System.out.println("ID: " + condition.getId());
            System.out.println("名称: " + condition.getName());
            System.out.println("目标: " + condition.getTargetRef());
            System.out.println("表达式: " + (condition.getExpression() != null ? condition.getExpression() : "无"));
            System.out.println("类型: " + condition.getExpressionType());
            System.out.println("是否默认: " + condition.isDefaultFlow());
            System.out.println("---------------------");
        }
        return conditions;
    }

}
